using System;
using System.Collections.Generic;
using System.Text;

namespace Tyng.Data
{
    /// <summary>
    /// Helper class for T-SQL string generation
    /// </summary>
    public static class TSqlHelper
    {
        /// <summary>
        /// Get a string representation of a typed .NET value.
        /// </summary>
        /// <param name="data">Value to get string for</param>
        /// <returns>T-SQL string representation of data</returns>
        public static string GetStringRepresentation(object data)
        {
            string s = string.Empty;

            if (data == null || Convert.IsDBNull(data))
                s = "NULL";
            else if (data is string)
                s = "N'" + ((string)data).Replace("'", "''") + "'";
            else if (data is bool)
            {
                if ((bool)data)
                    s = "1";
                else
                    s = "0";
            }
            else if (
                data is Guid ||
                data is DateTime)
            {
                s = "'" + data.ToString() + "'";
            }
            else if (
                data is Byte ||
                data is Int16 ||
                data is Int32 ||
                data is Int64 ||
                data is Decimal ||
                data is Double ||
                data is Single)
                s = data.ToString();
            else if (data is byte[])
                s = Environment.NewLine + "0x" + ToHexString((byte[])data) + Environment.NewLine;
            else
                throw new NotSupportedException(string.Format("Data type of '{1}' with value of '{0}' not supported", data, data.GetType()));

            return s;
        }

        static char[] hexDigits = {
									  '0', '1', '2', '3', '4', '5', '6', '7',
									  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        private static string ToHexString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length * 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                int b = bytes[i];
                chars[i * 2] = hexDigits[b >> 4];
                chars[i * 2 + 1] = hexDigits[b & 0xF];
            }
            return new string(chars);
        }
    }
}
